import React from 'react';
import { connect } from 'dva';
import { TableC, NoDataC } from '../comps';

class OperateTableDemo extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      columns: [],
      dataSource: [],
      numInPage: 20,
      currentPage: 1,
      total: 0,
      tableType: '', // 请求表格数据的名称
      queryId: '', // 请求表格数据的入参
    };
  }

  componentDidMount() {
    this.setState(
      {
        tableType: this.props.tableType,
        queryId: this.props.queryId,
      },
      () => {
        this.getTableData();
      },
    );
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.props.tableType != nextProps.tableType || this.props.queryId != nextProps.queryId) {
      this.setState(
        {
          tableType: nextProps.tableType,
          queryId: nextProps.queryId,
        },
        () => {
          this.getTableData();
        },
      );
    }
  }

  // 获取表格数据
  getTableData = () => {
    const { currentPage, numInPage, tableType, queryId } = this.state;
    this.props.dispatch({
      type: `operationM/${tableType}`,
      payload: {
        queryId,
        currentPage,
        numInPage,
      },
      callback: (type, data) => {
        if (type == 'success') {
          this.setState({
            columns: data.columns,
            dataSource: data.dataSource,
            total: data.pageInfo.total,
          });
        }
      },
    });
  };

  // 表格页码排序改变调用
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.getTableData();
      },
    );
  };

  render() {
    const { columns, dataSource, currentPage, numInPage, total, tableType } = this.state;
    return (
      <div style={{ padding: '20px' }}>
        {tableType ? (
          <TableC
            columns={columns}
            pagination={true}
            scroll={{ x: 'max-content' }}
            current={currentPage}
            pageSize={numInPage}
            dataSource={dataSource}
            rowKey={'name'}
            total={total}
            loading={this.props.loading.effects[`operationM/${tableType}`]}
            onChange={this.handleTableChange}
          />
        ) : (
          <NoDataC />
        )}
      </div>
    );
  }
}
export default connect(({ operationM, loading }) => ({ operationM, loading }))(OperateTableDemo);
